<template>
  <div class="UserInfo">
    <!-- <el-button size="small" type="primary" @click="appendBigLevel">新增大类</el-button> -->
    <el-row :style="{
    'margin-left': '42px',
    'height': '30px',
    'display': 'flex',
    'align-items': 'center'}">
      <!-- <el-col :span="5" >分类</el-col> -->
      <el-col :span="5">描述</el-col>
      <!-- <el-col :span="4">数据类型</el-col>
      <el-col :span="4">有效性</el-col> -->
      <el-col :span="10">操作</el-col>
    </el-row>
    <el-tree
      ref="tree"
      :key="treeKey"
      :data="data"
      node-key="id"
      :expand-on-click-node="false"
      :render-content="renderContent"
      :lazy="true"
      :load="loadTreeNode"
      :default-expanded-keys="treeExpandedKeys"
      @node-expand="treeExpand"
      @node-collapse="treeCollapse">
    </el-tree>
    <BaseDialog
      :visible.sync="isShowDlg"
      :title="dialogTitle"
      destroyOnClose
      width="1050"
      :containerStyle="{height: '100%', overflow: 'auto'}">
      <SourceDetail :type="editType" :list="allList" :rowData="activeData" @close="closeHandler"></SourceDetail>
    </BaseDialog>
  </div>
</template>

<script>
import SourceDetail from './SourceDetail'
import { getInfoWaysNext, updateInfoWays } from '@/api/potenCus/basedata/knowWays'
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
export default {
  name: 'knowWays',
  mixins: [dictionary],
  components: {
    SourceDetail
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'upClueName',
        label: 'label',
        isLeaf: 'leaf'
      },
      activeData: null,   // 当前操作数据
      editType: '',
      treeExpandedKeys: [],   // 记录打开节点的数组
      treeKey: '',    // 控制tree渲染的key
      nodeQuery: {
        name: ''    // 编辑树节点表单的model
      },
      isShowDlg: false,    // 是否显示编辑节点弹框
      dialogTitle: '', // 浮动窗口名称(新增，编辑)
      allList: [], // 放所有数据内容
    }
  },
  mounted () {
    // this.init();
  },
  methods: {
    // 加载树
    loadTreeNode(node, resolve) {
        const id = node ? node.data.id : '';
        let params = {}
        if (node.level === 0) {
          params = {
            upId: '' // 带上当前展开树的id
          }
        } else {
          params = {
            upId: id // 带上当前展开树的id
          }
        }
        // getInfoWaysNext
        getInfoWaysNext(params).then(res => {
            let treeData = res.data;
            if (res.success && node.wayLevel === 0) {
              // 如果是第一次加载数据，直接返回数据
              treeData.forEach(item=>{
                item['leaf'] = !item.hasNext
              })
              resolve(treeData);
            } else if(res.success) {
              // 如果非第一次加载数据，将返回数据拼接到操作节点的childList属性中
              node.data.childList = treeData;
              treeData.forEach(item=>{
                item['leaf'] = !item.hasNext
              })
              resolve(treeData);
            } else {
              resolve([]);
              this.$message({
                  type: 'error',
                  message: '加载数据出错！'
              });
            }
        });
    },
    // 刷新key值，重新渲染tree
    renderTree() {
      this.treeKey = +new Date();
    },
    init () {
      let params = {
        level: 1, // 只有查询一级树有值：1
        upId: '' // 带上当前展开树的id
      }
      this.queryLevel(params)
    },
    queryLevel (params){
      getInfoWaysNext(params).then(res => {
        this.data = res.data && res.data.length > 0 ? res.data: []
        this.data.forEach(item=>{
          item.hasNext ? item.children = [{}] : ''
        })
      });
    },
    // 新增来源大类
    appendBigLevel(){
      this.editType = "ADD";
      this.isShowDlg = true;
      this.dialogTitle = "新增来源大类";
      this.activeData = {
        clueLevel: 0, // 无上级来源
        upClueId: null
      }
    },
    // 新增节点
    append(node, data) {
      this.editType = "ADD";
      this.isShowDlg = true;
      // 记录当前节点数据，供新增弹框关闭后回调用
      this.activeData = data;
      this.dialogTitle = "新增了解途径"
    },
    // 编辑节点
    modify(node, data){
      this.nodeQuery.name = data.name;
      // 记录当前操作数据
      this.activeData = data;
      this.editType = "EDIT";
      this.isShowDlg = true;
      this.dialogTitle = "编辑了解途径"
    },
    remove(node, data) {
      let params = [{
        id: data.id,
        deleted: true
      }]
      updateInfoWays(params).then(res => {
        if ( res.success) {
          // 重新渲染tree
          this.renderTree();
          this.$message({
              type: "success",
              message: "删除成功!"
          });
        }
      });
    },
    renderContent(h, { node, data, store }) {
      let { preDictHandler } = this
      if (this.allList.length == 0) {
        this.allList.push({value:data.id, text:data.wayName})
      } else {
        this.allList.some(item=> item.value == data.id)?'':this.allList.push({value:data.id, text:data.wayName})
      }
      return (
        // <span class="custom-tree-node">
          <el-row style="width:100%;line-height:200%;" slot-scope="{ node, data }">
            <el-col span={5}>{data.wayName ||'_'}</el-col>
            <el-col span={6}>
              <div class="grid-content bg-purple-dark">
                <span>
                  <el-button size="mini" type="text" on-click={ () => this.append(node,data) }>新增下级字段</el-button>
                  {node.level!=1?<el-button size="mini" type="text" disabled={ node.level!=1?false:true }on-click={ () => node.level != 1 ? this.modify(node, data) : '' }>修改</el-button>:''}
                  {node.level!=1?<el-button size="mini" type="text" disabled={ node.level!=1&&data.leaf?false:true} on-click={ () => node.level!=1&&data.leaf?this.remove(node, data):'' }>删除</el-button>:''}
                </span>
              </div>
            </el-col>
          </el-row>
        // </span>
        );
    },
    // 新增节点回调函数
    appendCallback() {
      const data = this.activeData;
      const nodeQuery = this.nodeQuery;
      nodeQuery.parentId = data.id === '0' ? '' : data.id;
    },
    // 编辑节点回调函数
    editCallback() {
      const data = this.activeData,
      nodeQuery = this.nodeQuery;
      data.name = nodeQuery.name;
      // let params= {
      //   "clueLevel": 0,
      //   "clueName": "string",
      //   "dataSources": 0,
      //   "dataType": 0,
      //   "id": 0,
      //   "isEnable": 0,
      //   "ownerCode": "string",
      //   "remark": "string",
      //   "upClueId": 0
      // }
      // 将节点新名称和节点id传递到后台
      // TODO:
      // editClueSource(params).then(res => {
      //   const result = res.data;
      //   if (result && res.success) {
      //     this.$message({
      //       type: "success",
      //       message: "修改成功！"
      //     });
      //     this.renderTree();
      //   }
      // });
    },
    treeExpand(data, node, component){
      if (!data.leaf) { // 不是叶子节点
        this.treeExpandedKeys.push(data.id);
      }
    },
    // 当节点关闭时，移除节点的id
    treeCollapse(data) {
      const index = this.treeExpandedKeys.indexOf(data.id);
      if (index > -1) {
        this.treeExpandedKeys.splice(index, 1);
      }
    },
    // tree node 弹框取消事件
    reset() {
      this.activeData = null;
      this.isShowDlg = false;
      this.nodeQuery = {
          name: "",
          parentId: ""
      };
      this.editType = "ADD";
    },
    closeHandler(ifShow, ifRender) {
      this.isShowDlg = ifShow;
      if (ifRender) {
        this.renderTree();
      }
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
  },
};
</script>

<style lang="less" scoped>
</style>
